package com.yc.vote.util;

import com.yc.vote.biz.BizException;
import com.yc.vote.entity.Result;

import com.google.gson.Gson;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class Utils {
    /**
     * Servlet 调用业务方法的模板函数
     *
     * @param successMsg    执行成功时, 返回的消息
     * @param response
     * @param handler       不返回结果对象
     * @throws IOException
     */
    public static void result(String successMsg,
                              HttpServletResponse response,
                              ResultHandler handler) throws IOException {
        Result result;
        try {
            handler.handle();
            result = new Result(1, successMsg, null);
        } catch (BizException e) {
            e.printStackTrace();
            result = new Result(0, e.getMessage(), null);
        } catch (Exception e) {
            e.printStackTrace();
            result = new Result(0, "系统异常, 请联系管理员!", null);
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().append(new Gson().toJson(result));
    }

    /**
     * Servlet 调用业务方法的模板函数
     *
     * @param successMsg    执行成功时, 返回的消息
     * @param response
     * @param handler       返回结果对象
     * @throws IOException
     */
    public static void result(String successMsg,
                              HttpServletResponse response,
                              ResultHandlerWithReturn handler) throws IOException {
        Result result;
        try {
            Object res = handler.handle();
            result = new Result(1, successMsg, res);
        } catch (BizException e) {
            e.printStackTrace();
            result = new Result(0, e.getMessage(), null);
        } catch (Exception e) {
            e.printStackTrace();
            result = new Result(0, "系统异常, 请联系管理员!", null);
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().append(new Gson().toJson(result));
    }

    // 回调接口 ( 业务方法不返回结果 ) => 函数接口
    public static interface ResultHandler {
        void handle() throws BizException;
    }

    // 回调接口 ( 业务方法返回结果 )  => 函数接口
    public static interface ResultHandlerWithReturn {
        Object handle() throws BizException;
    }

}
